package info.sybian.web;

import info.sybian.service.DoMF;
import info.sybian.util.Services;

import java.io.File;
import java.io.IOException;

import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import objot.container.Container;

import com.sleepycat.je.DatabaseConfig;
import com.sleepycat.je.Durability;
import com.sleepycat.je.Environment;
import com.sleepycat.je.EnvironmentConfig;
import com.sleepycat.persist.EntityStore;

/**
 * LGPL V3
 * 
 * @author nkadun
 */
public class SybianServlet implements Servlet {
	private ServletConfig config;
	private Environment env;
	private EntityStore store;
	private Container con;

	@Override
	public void destroy() {
		if(store != null)
			store.close();
		if(env != null)
			env.close();
	}

	@Override
	public ServletConfig getServletConfig() {
		return config;
	}

	@Override
	public String getServletInfo() {
		return "Sybian servlet";
	}

	@Override
	public void init(ServletConfig c) throws ServletException {
		config = c;
		EnvironmentConfig envConfig = new EnvironmentConfig();
		envConfig.setAllowCreate(true);
		envConfig.setTransactional(true);
		envConfig.setDurability(Durability.COMMIT_NO_SYNC);
		env = new Environment(new File("/home/nkadun/sybian-data"), envConfig);

		DatabaseConfig dc = new DatabaseConfig();
		dc.setAllowCreate(true);
		dc.setTransactional(true);

		// StoreConfig storeConfig = new StoreConfig();
		// storeConfig.setAllowCreate(true);
		// storeConfig.setTransactional(true);
		// store = new EntityStore(env, "user", storeConfig);

		try {
			con = Services.build(env, dc);
		}
		catch(Exception e) {
			throw new ServletException(e);
		}
	}

	@Override
	public void service(ServletRequest req, ServletResponse res) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest)req;
		String uri = request.getRequestURI();
		String jsp = null;

		// get container in http session
		HttpSession hse = request.getSession();
		Container s = (Container)hse.getAttribute("$CONTAINER");
		if(s == null)
			hse.setAttribute("$CONTAINER", s = con.parent().create());

		// create copy of request container
		Container r = con.create(s);

		if(uri.endsWith("init")) {
			try {
				jsp = r.get(DoMF.class).init();
			}
			catch(Exception e) {
				throw new ServletException(e);
			}
		}

		req.getRequestDispatcher("/WEB-INF/jsp/" + jsp + ".jsp").forward(req, res);
	}
}
